#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <ctype.h>
#include "option.h"
#include "myerr.h"

struct MystarOption opt = {
    NULL,NULL,NULL,NULL,
    0,0,0,0
};

extern int isblank(int c);

//去掉字符串的头尾空白符
char * strip(char * str){
    char *val;
    while (isblank(*str)) ++str;
    val = str;
    str += strlen(str) - 1;
    while (isblank(*str) || *str == '\r' || *str == '\n') --str;
    *(str+1) = '\0';
    return val;
}

//将字符串转为小写
char * strlow(char * str){
    char * val = str;
    while (*str != '\0'){
        *str = tolower(*str);
        ++str;
    }
    return val;
}

void copy(char ** dest, char * src){
    if (*dest != NULL) free(*dest);
    *dest = strdup(src);
}

int readConfigFromFile(){
    FILE  *fp;
    char  buf[4096];
    char  *param, *value;
    
    ///检测并解析mystar.conf
    //TODO:this may be improved in the later version.
    if ((fp=fopen("./mystar.conf","r"))==NULL ){
        if( (fp=fopen("/etc/mystar.conf","r"))==NULL ){
            fprintf(stderr, "cannot open file mystar.conf ! check it.\n");
            return 1;
        }
    }
    while(fgets(buf,sizeof(buf),fp)!=NULL){
        //跳过注释和空白行
        if ( (buf[0]=='#') || (buf[0]=='\n') )
            continue;
        //判断是否为参数行
        value = strchr(buf, '=');
        if (value == NULL || value == buf)
            continue;
        //分割参数字符串
        *value++ = '\0';
        param = strlow(strip(buf));
        value = strip(value);
        //逐一扫描匹配
        if (strcmp(param,"name")==0)
            copy(&opt.username, value);
        if (strcmp(param,"username")==0)
            copy(&opt.username, value);
        else if (strcmp(param,"password")==0)
            copy(&opt.password, value);
        else if (strcmp(param,"nic")==0)
            copy(&opt.nic, value);
        else if(strcmp(param,"fakeip")==0){
            //if (opt.fakeAddress != NULL) free(opt.fakeAddress);
            opt.fakeip = strdup(value);
            /*
            if( inet_pton(AF_INET,fakeAddress,m_ip)<=0 )
                err_msg("invalid fakeAddress found in mystar.conf, ignored...\n");
            else m_fakeAddress=fakeAddress;*/
        }
        else if (strcmp(param,"authenticationmode")==0)
            opt.mode = atoi(value)? 1 : 0;
        else if (strcmp(param,"mode")==0)
            opt.mode = atoi(value)? 1 : 0;
        else if(strcmp(param,"interval")==0)
            opt.interval = atoi(value)? 1 : 0;
        else if(strcmp(param,"echointerval")==0)
            opt.interval = atoi(value)? 1 : 0;
        else if(strcmp(param,"reconnect")==0)
            opt.reconnect = atoi(value)? 1 : 0;
        else if (strcmp(param,"silent")==0)
            opt.silent = atoi(value)? 1 : 0;
        continue;
    }
    
    if (ferror(fp)) return fprintf(stderr, "cannot read mystar.conf ! check it.\n") || 1;
    fclose(fp);
    #ifdef MYSTAR_DEBUG
    printf("username=%s\n",opt.username);
    printf("password=%s\n",opt.password);
    printf("nic=%s\n",opt.nic);
    printf("Mode=%d\n",opt.mode);
    printf("Interval=%d\n",opt.interval);
    printf("Reconnect=%d\n",opt.reconnect);//NOT supported now!!
    printf("fake ip=%s\n",opt.fakeip);
    #endif
    //just set them to zero since they don't seem to be important.
    //memset(m_netgate,0,sizeof(m_netgate));
    //memset(m_dns1,0,sizeof(m_dns1));
    return 0;
}


//TODO:命令行参数解析
int readConfigFromCmd(int argc, char * argv[]){
    extern int  optind;
    extern int  opterr;
    extern char *optarg;
    int optVal;                         // 保存参数值
    static char shortOpts[] = "u:p:n:f:m:i:r:s:";//短参数 
    static struct option opts[] = {     // 所支持的参数选项
        {"username", 1 ,NULL ,'u'},
        {"password", 1 ,NULL ,'p'},
        {"nic", 1 ,NULL ,'n'},
        {"fakeip", 1 ,NULL ,'f'},
        {"mode", 1 ,NULL ,'m'},
        {"interval", 1 ,NULL ,'i'},
        {"reconnect", 1 ,NULL ,'r'},
        {"silent", 1 ,NULL ,'s'},
        {NULL, 0 ,NULL ,0}
    };
    // 开始解析参数
    optind = 1;
    optVal = 0;
    while ( (optVal = getopt_long(argc, argv, shortOpts, opts, NULL)) != -1){
        switch(optVal){
            case 0:                     // option ends
                break;
            case 'u':                   // username
                copy(&opt.username, optarg);
                break;
            case 'p':
                copy(&opt.password, optarg);
                break;
            case 'n':
                copy(&opt.nic, optarg);
                break;
            case 'f':
                copy(&opt.fakeip, optarg);
                break;
            case 'm':
                opt.mode = atoi(optarg)?1:0;
                break;
            case 'i':
                opt.interval = atoi(optarg)?1:0;
                break;
            case 'r':
                opt.reconnect = atoi(optarg)?1:0;
                break;
            case 's': 
                opt.silent = atoi(optarg)?1:0;
            default:
                break;
        }
    }
    return 0;
}
